<template>
  <div class="pan-assets-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="header-actions">
        <el-button @click="handleRefresh">刷新</el-button>
        <!-- <el-button @click="handleExport" :disabled="assetList.length === 0">
          导出CSV
        </el-button> -->
        <el-button @click="handleViewStatistics"> 统计分析 </el-button>
        <el-button @click="handleClearExpiredCache"> 清理过期缓存 </el-button>
      </div>
    </div>

    <!-- 全局统计卡片区域 -->
    <el-card class="stats-card" :body-style="{ padding: '15px' }">
      <div class="stats-container">
        <StatisticCard
          label="总资产"
          :value="stats.total.toString()"
          icon="el-icon-document"
          type="primary"
          :trend="stats.totalTrend"
        />
        <StatisticCard
          label="高风险"
          :value="stats.highRisk.toString()"
          icon="el-icon-warning"
          type="danger"
          :subtitle="`${stats.highRiskPercent}%`"
        />
        <StatisticCard
          label="待处理"
          :value="stats.pending.toString()"
          icon="el-icon-time"
          type="info"
        />
        <StatisticCard
          label="已确认"
          :value="stats.confirmed.toString()"
          icon="el-icon-check"
          type="success"
          :subtitle="`${stats.confirmedPercent}%`"
        />
        <StatisticCard
          label="已忽略"
          :value="stats.ignored.toString()"
          icon="el-icon-close"
          type="warning"
          :subtitle="`${stats.ignoredPercent}%`"
        />
        <StatisticCard
          label="处理率"
          :value="`${stats.processRate}%`"
          icon="el-icon-data-line"
          type="success"
        />
      </div>
    </el-card>

    <!-- 筛选区域 -->
    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <div v-if="isFilterExpanded" class="filter-content">
        <DynamicForm
          ref="searchFormRef"
          v-model="filterForm"
          :form-config="filterFormConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </el-card>

    <!-- 疑似资产列表 -->
    <el-card class="table-card" :body-style="{ padding: '15px' }">
      <div class="list-header">
        <div class="header-left">
          <span class="selected-count" v-if="selectedIds.length > 0">
            已选择 {{ selectedIds.length }} 个资产
          </span>
          <el-button
            type="success"
            :disabled="selectedIds.length === 0"
            @click="handleBatchConfirm"
            style="margin-left: 10px"
          >
            批量确认 ({{ selectedIds.length }})
          </el-button>
          <el-button
            type="warning"
            :disabled="selectedIds.length === 0"
            @click="handleBatchIgnore"
            style="margin-left: 10px"
          >
            批量忽略 ({{ selectedIds.length }})
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedIds.length === 0"
            @click="handleBatchDelete"
            style="margin-left: 10px"
          >
            批量删除 ({{ selectedIds.length }})
          </el-button>
        </div>
        <div class="header-right">
          <span class="sort-label">排序:</span>
          <el-select
            v-model="filterForm.sort_by"
            size="small"
            style="width: 140px; margin-right: 10px"
            @change="handleSearch"
          >
            <el-option label="按检测时间" value="detected_time" />
            <el-option label="按风险分数" value="risk_score" />
            <el-option label="按文件名" value="filename" />
          </el-select>
          <el-select
            v-model="filterForm.sort_order"
            size="small"
            style="width: 80px"
            @change="handleSearch"
          >
            <el-option label="升序" value="asc" />
            <el-option label="降序" value="desc" />
          </el-select>
        </div>
      </div>

      <div v-loading="loading" class="table-wrapper">
        <DynamicTable
          :data="assetList"
          :columns="tableColumns"
          :loading="false"
          border
          row-key="id"
          selection-type="multiple"
          @selection-change="handleSelectionChange"
        >
          <template #filename="{ row }">
            <div class="filename-cell">
              <span class="file-icon">📄</span>
              <span class="filename-text">{{
                row.filename || row.file_name || "-"
              }}</span>
            </div>
            <div
              class="file-meta"
              v-if="row.asset_keyword || row.keyword || row.scene_name"
            >
              <span v-if="row.asset_keyword || row.keyword" class="meta-item">
                关键词: {{ row.asset_keyword || row.keyword }}
              </span>
              <span v-if="row.scene_name" class="meta-item">
                场景: {{ row.scene_name }}
              </span>
              <span
                v-if="row.detected_time || row.created_time"
                class="meta-item"
              >
                检测: {{ row.detected_time || row.created_time }}
              </span>
            </div>
          </template>

          <template #risk_level="{ row }">
            <div class="risk-cell">
              <span class="risk-score">{{ row.risk_score || 0 }}</span>
              <el-tag
                :type="getRiskLevelType(row.risk_level)"
                size="small"
                style="margin-left: 4px"
              >
                {{ getRiskLevelText(row.risk_level) }}
              </el-tag>
            </div>
          </template>

          <template #asset_status="{ row }">
            <el-tag
              :type="getStatusType(row.asset_status || row.review_status)"
              size="small"
            >
              {{ getStatusText(row.asset_status || row.review_status) }}
            </el-tag>
          </template>

          <template #size="{ row }">
            <span v-if="row.size_mb"> {{ row.size_mb }} MB </span>
            <span v-else-if="row.size">
              {{ formatSize(row.size) }}
            </span>
            <span v-else class="no-data">-</span>
          </template>

          <template #department="{ row }">
            <div v-if="row.confirmed_department">
              {{ row.confirmed_department }}
              <div v-if="row.confirmed_person" class="person-name">
                {{ row.confirmed_person }}
              </div>
            </div>
            <span v-else class="no-data">-</span>
          </template>

          <template #action="{ row }">
            <div class="action-buttons">
              <el-button
                size="small"
                type="primary"
                @click="handleViewDetail(row)"
              >
                详情
              </el-button>
              <el-button
                size="small"
                type="primary"
                @click="handleExportDetail(row)"
              >
                导出
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleClearTaskCache(row.id)"
              >
                清理任务缓存
              </el-button>
            </div>
          </template>
        </DynamicTable>

        <el-empty
          v-if="!loading && assetList.length === 0"
          description="暂无资产数据"
        />
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="pagination.total > 0">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="pagination.pageSizes"
          :total="pagination.total"
          :layout="pagination.layout"
          :background="pagination.background"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 资产详情弹窗 -->
    <DetailModal
      v-model="detailVisible"
      :asset-id="currentAssetId"
      :detail-data="detailData"
      :loading="detailLoading"
    />

    <!-- 批量确认弹窗 -->
    <BatchConfirmModal
      v-model="batchConfirmVisible"
      :selected-ids="selectedIds"
      :department-options="props.departmentOptions"
      @success="handleBatchConfirmSuccess"
    />

    <!-- 批量忽略弹窗 -->
    <BatchIgnoreModal
      v-model="batchIgnoreVisible"
      :selected-ids="selectedIds"
      @success="handleBatchIgnoreSuccess"
    />

    <!-- 批量删除弹窗 -->
    <BatchDeleteModal
      v-model="batchDeleteVisible"
      :selected-ids="selectedIds"
      @success="handleBatchDeleteSuccess"
    />

    <!-- 统计分析弹窗 -->
    <StatisticsModal
      v-model="statisticsVisible"
      :department-options="props.departmentOptions"
    />

    <!-- 导出详情弹窗 -->
    <ExportDetailModal
      v-model="exportDetailVisible"
      :asset-id="currentExportAssetId"
      @success="handleExportDetailSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import StatisticCard from "./components/StatisticCard.vue";
import {
  getPanAssets,
  getPanAssetDetail,
  exportPanAssets,
  clearExpiredCache,
  clearTaskCache,
} from "../../servers";
import DetailModal from "./components/DetailModal.vue";
import BatchConfirmModal from "./components/BatchConfirmModal.vue";
import BatchIgnoreModal from "./components/BatchIgnoreModal.vue";
import BatchDeleteModal from "./components/BatchDeleteModal.vue";
import StatisticsModal from "./components/StatisticsModal.vue";
import ExportDetailModal from "./components/ExportDetailModal.vue";
import { Refresh } from "@element-plus/icons-vue";

// 定义props
const props = defineProps<{
  task?: string;
  departmentOptions?: Array<{ label: string; value: string }>;
}>();

const route = useRoute();
const router = useRouter();

// 页面状态
const isFilterExpanded = ref(true);
const loading = ref(false);
const selectedIds = ref<number[]>([]);
const detailVisible = ref(false);
const currentAssetId = ref<number | null>(null);
const detailData = ref<any>(null);
const detailLoading = ref(false);
const exportDetailVisible = ref(false);
const currentExportAssetId = ref<number | null>(null);
const batchConfirmVisible = ref(false);
const batchIgnoreVisible = ref(false);
const batchDeleteVisible = ref(false);
const statisticsVisible = ref(false);

// 统计信息
const stats = reactive({
  total: 0,
  highRisk: 0,
  pending: 0,
  confirmed: 0,
  ignored: 0,
  totalTrend: "",
  highRiskPercent: "0.0",
  confirmedPercent: "0.0",
  ignoredPercent: "0.0",
  processRate: "0.0",
});

// 疑似资产列表数据
const assetList = ref<Array<any>>([]);

// 部门列表（从props获取）
const departmentOptions = computed(() => props.departmentOptions || []);

// 筛选表单
const searchFormRef = ref<DynamicFormInstance>();
const filterForm = reactive({
  keyword: "",
  risk_level: "",
  status: "",
  scene_type: "",
  department: "",
  start_date: "",
  source_type: "pan",
  end_date: "",
  sort_by: "detected_time",
  sort_order: "desc" as "asc" | "desc",
});

// 筛选表单配置
const filterFormConfig = computed<FormItemConfig[]>(() => [
  {
    key: "keyword",
    name: "文件名关键词",
    type: "input",
    placeholder: "请输入文件名关键词",
    col: { span: 6 },
  },
  {
    key: "risk_level",
    name: "风险等级",
    type: "select",
    placeholder: "全部",
    params: { clearable: true },
    options: [
      { label: "全部", value: "" },
      { label: "极高", value: "critical" },
      { label: "高", value: "high" },
      { label: "中", value: "medium" },
      { label: "低", value: "low" },
    ],
    col: { span: 6 },
  },
  {
    key: "status",
    name: "审核状态",
    type: "select",
    placeholder: "全部",
    params: { clearable: true },
    options: [
      { label: "全部", value: "" },
      { label: "待处理", value: "pending" },
      { label: "已确认", value: "confirmed" },
      { label: "已忽略", value: "ignored" },
    ],
    col: { span: 6 },
  },
  {
    key: "scene_type",
    name: "场景类型",
    type: "select",
    placeholder: "全部",
    params: { clearable: true },
    options: [
      { label: "全部", value: "" },
      { label: "财务敏感", value: "financial" },
      { label: "人事信息", value: "hr" },
      { label: "合同文件", value: "contract" },
      { label: "技术文档", value: "technical" },
    ],
    col: { span: 6 },
  },
  {
    key: "department",
    name: "责任部门",
    type: "select",
    placeholder: "请选择责任部门",
    params: { clearable: true },
    options: [
      { label: "全部", value: "" },
      ...(Array.isArray(departmentOptions.value)
        ? departmentOptions.value
        : []),
    ],
    col: { span: 6 },
  },
  // {
  //   key: "start_date",
  //   name: "开始日期",
  //   type: "date",
  //   placeholder: "选择开始日期",
  //   params: { valueFormat: "YYYY-MM-DD" },
  //   col: { span: 6 },
  // },
  // {
  //   key: "end_date",
  //   name: "结束日期",
  //   type: "date",
  //   placeholder: "选择结束日期",
  //   params: { valueFormat: "YYYY-MM-DD" },
  //   col: { span: 6 },
  // },
]);

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    label: "文件名",
    prop: "filename",
    minWidth: 250,
    fixed: "left",
    showOverflowTooltip: true,
    slot: "filename",
  },
  {
    label: "大小",
    prop: "size",
    width: 120,
    align: "center",
    slot: "size",
  },
  {
    label: "风险",
    prop: "risk_level",
    width: 100,
    align: "center",
    slot: "risk_level",
  },
  {
    label: "状态",
    prop: "asset_status",
    width: 100,
    align: "center",
    slot: "asset_status",
  },
  {
    label: "部门",
    prop: "confirmed_department",
    minWidth: 120,
    slot: "department",
  },
  {
    label: "关键词",
    prop: "asset_keyword",
    minWidth: 120,
    formatter: (row: any) => row.asset_keyword || row.keyword || "-",
  },
  {
    label: "场景类型",
    prop: "scene_name",
    minWidth: 120,
  },
  {
    label: "检测时间",
    prop: "detected_time",
    minWidth: 160,
    formatter: (row: any) => row.detected_time || row.created_time || "-",
  },
  {
    label: "操作",
    width: 260,
    fixed: "right",
    slot: "action",
  },
];

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

// 获取状态标签类型
const getStatusType = (
  status: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    pending: "info",
    confirmed: "success",
    ignored: "warning",
  };
  return typeMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string): string => {
  const textMap: Record<string, string> = {
    pending: "待处理",
    confirmed: "已确认",
    ignored: "已忽略",
  };
  return textMap[status] || status;
};

// 获取风险等级类型
const getRiskLevelType = (
  level: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    critical: "danger",
    high: "danger",
    medium: "warning",
    low: "success",
  };
  return typeMap[level] || "info";
};

// 获取风险等级文本
const getRiskLevelText = (level: string): string => {
  const textMap: Record<string, string> = {
    critical: "极高",
    high: "高",
    medium: "中",
    low: "低",
  };
  return textMap[level] || level;
};

// 格式化文件大小
const formatSize = (bytes: number): string => {
  if (!bytes) return "0 B";
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
  if (bytes < 1024 * 1024 * 1024)
    return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
};

// 获取资产列表
const fetchAssetList = async (values?: any) => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      sort_by: filterForm.sort_by,
      sort_order: filterForm.sort_order,
      ...values,
    };

    // 处理筛选参数
    if (filterForm.keyword) {
      params.keyword = filterForm.keyword;
    }
    if (filterForm.risk_level) {
      params.risk_level = filterForm.risk_level;
    }
    if (filterForm.status) {
      params.status = filterForm.status;
    }
    if (filterForm.scene_type) {
      params.scene_type = filterForm.scene_type;
    }
    if (filterForm.department) {
      params.department = filterForm.department;
    }
    if (filterForm.start_date) {
      params.start_date = filterForm.start_date;
    }
    if (filterForm.end_date) {
      params.end_date = filterForm.end_date;
    }
    if (filterForm.source_type) {
      params.source_type = filterForm.source_type;
    }

    const result = await getPanAssets(params);

    // 更新列表数据
    if (result.data.assets && Array.isArray(result.data.assets)) {
      assetList.value = result.data.assets;
    }

    // 更新分页信息
    if (result.data.pagination) {
      pagination.total = result.data.pagination.total || 0;
      pagination.currentPage =
        result.data.pagination.page || pagination.currentPage;
      pagination.pageSize =
        result.data.pagination.per_page || pagination.pageSize;
    } else if (result.data.total !== undefined) {
      // 如果没有 pagination 对象，但有 total 字段
      pagination.total = result.data.total;
    }

    // 更新统计信息（从响应中获取或计算）
    updateStats(result.data);
  } catch (error: any) {
    ElMessage.error(error?.message || "获取资产列表失败");
  } finally {
    loading.value = false;
  }
};

// 更新统计信息
const updateStats = (data: any) => {
  // 从响应数据中获取统计信息，如果没有则从列表计算
  if (data.stats) {
    stats.total = data.stats.total || 0;
    stats.highRisk = data.stats.high_risk || 0;
    stats.pending = data.stats.pending || 0;
    stats.confirmed = data.stats.confirmed || 0;
    stats.ignored = data.stats.ignored || 0;
  } else {
    // 从列表数据计算统计（如果接口返回了总数，使用总数；否则使用当前页数据估算）
    stats.total =
      data.pagination?.total || pagination.total || assetList.value.length;

    // 如果总数很大但当前页数据少，只计算当前页的统计（作为参考）
    if (assetList.value.length > 0) {
      const currentPageHighRisk = assetList.value.filter(
        (item) => item.risk_level === "critical" || item.risk_level === "high"
      ).length;
      const currentPagePending = assetList.value.filter(
        (item) => (item.asset_status || item.review_status) === "pending"
      ).length;
      const currentPageConfirmed = assetList.value.filter(
        (item) => (item.asset_status || item.review_status) === "confirmed"
      ).length;
      const currentPageIgnored = assetList.value.filter(
        (item) =>
          (item.asset_status || item.review_status) === "ignored" ||
          item.is_ignored
      ).length;

      // 如果总数已知，按比例估算；否则使用当前页数据
      if (stats.total > assetList.value.length) {
        const ratio = stats.total / assetList.value.length;
        stats.highRisk = Math.round(currentPageHighRisk * ratio);
        stats.pending = Math.round(currentPagePending * ratio);
        stats.confirmed = Math.round(currentPageConfirmed * ratio);
        stats.ignored = Math.round(currentPageIgnored * ratio);
      } else {
        stats.highRisk = currentPageHighRisk;
        stats.pending = currentPagePending;
        stats.confirmed = currentPageConfirmed;
        stats.ignored = currentPageIgnored;
      }
    }
  }

  // 计算百分比
  if (stats.total > 0) {
    stats.highRiskPercent = ((stats.highRisk / stats.total) * 100).toFixed(1);
    stats.confirmedPercent = ((stats.confirmed / stats.total) * 100).toFixed(1);
    stats.ignoredPercent = ((stats.ignored / stats.total) * 100).toFixed(1);
    stats.processRate = (
      ((stats.confirmed + stats.ignored) / stats.total) *
      100
    ).toFixed(1);
  } else {
    stats.highRiskPercent = "0.0";
    stats.confirmedPercent = "0.0";
    stats.ignoredPercent = "0.0";
    stats.processRate = "0.0";
  }
};

// 筛选操作
const handleReset = () => {
  searchFormRef.value?.resetFields();
  filterForm.keyword = "";
  filterForm.risk_level = "";
  filterForm.status = "";
  filterForm.scene_type = "";
  filterForm.department = "";
  filterForm.start_date = "";
  filterForm.end_date = "";
  filterForm.sort_by = "detected_time";
  filterForm.sort_order = "desc";
  filterForm.source_type = "pan";
  pagination.currentPage = 1;
  fetchAssetList();
};

const handleSearch = (values: any) => {
  pagination.currentPage = 1;
  fetchAssetList(values);
};

// 分页操作
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchAssetList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchAssetList();
};

// 获取资产详情
const fetchAssetDetail = async (assetId: number) => {
  if (!assetId) return;

  detailLoading.value = true;
  try {
    const result = await getPanAssetDetail(assetId);

    detailData.value = result.data;
  } catch (error: any) {
    ElMessage.error(error?.message || "获取资产详情失败");
    detailData.value = null;
  } finally {
    detailLoading.value = false;
  }
};

// 查看详情
const handleViewDetail = async (row: any) => {
  if (row.id) {
    currentAssetId.value = row.id;
    detailVisible.value = true;
    await fetchAssetDetail(row.id);
  } else {
    ElMessage.warning("资产ID不存在");
  }
};

// 导出详情
const handleExportDetail = (row: any) => {
  if (row.id) {
    currentExportAssetId.value = row.id;
    exportDetailVisible.value = true;
  } else {
    ElMessage.warning("资产ID不存在");
  }
};

// 导出详情成功
const handleExportDetailSuccess = () => {
  // 可以在这里添加成功后的处理逻辑
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map((item) => item.id);
};

// 导出
const handleExport = async () => {
  if (assetList.value.length === 0) {
    ElMessage.warning("没有可导出的数据");
    return;
  }

  try {
    const loading = ElLoading.service({ text: "正在导出数据..." });

    // 构建导出参数
    const params: any = {
      format: "xlsx",
    };

    // 如果有选中的资产，只导出选中的
    if (selectedIds.value.length > 0) {
      params.asset_ids = selectedIds.value.join(",");
    } else {
      // 否则使用当前筛选条件
      if (filterForm.keyword) {
        params.keyword = filterForm.keyword;
      }
      if (filterForm.risk_level) {
        params.risk_level = filterForm.risk_level;
      }
      if (filterForm.status) {
        params.status = filterForm.status;
      }
      if (filterForm.department) {
        params.department = filterForm.department;
      }
      if (filterForm.start_date) {
        params.start_date = filterForm.start_date;
      }
      if (filterForm.end_date) {
        params.end_date = filterForm.end_date;
      }
      if (filterForm.scene_type) {
        params.scene_type = filterForm.scene_type;
      }
      if (filterForm.source_type) {
        params.source_type = filterForm.source_type;
      }
    }

    const blob = await exportPanAssets(params);

    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    const date = new Date().toISOString().slice(0, 10).replace(/-/g, "");
    link.download = `网盘资产列表_${date}.xlsx`;
    link.style.visibility = "hidden";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);

    loading.close();
    ElMessage.success("导出成功");
  } catch (error: any) {
    ElMessage.error("导出失败：" + (error?.message || "未知错误"));
  }
};

// 查看统计分析
const handleViewStatistics = () => {
  statisticsVisible.value = true;
};

// 批量确认
const handleBatchConfirm = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning("请先选择要确认的资产");
    return;
  }
  batchConfirmVisible.value = true;
};

// 批量忽略
const handleBatchIgnore = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning("请先选择要忽略的资产");
    return;
  }
  batchIgnoreVisible.value = true;
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning("请先选择要删除的资产");
    return;
  }
  batchDeleteVisible.value = true;
};

// 批量确认成功
const handleBatchConfirmSuccess = () => {
  selectedIds.value = [];
  fetchAssetList();
};

// 批量忽略成功
const handleBatchIgnoreSuccess = () => {
  selectedIds.value = [];
  fetchAssetList();
};

// 批量删除成功
const handleBatchDeleteSuccess = () => {
  selectedIds.value = [];
  fetchAssetList();
};

// 刷新列表
const handleRefresh = () => {
  selectedIds.value = [];
  fetchAssetList();
};

// 清理过期缓存
const handleClearExpiredCache = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要清理所有过期缓存吗？此操作不可恢复。",
      "确认清理",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              const result = await clearExpiredCache({ dry_run: false });

              const { cleared_count, memory_freed_human, execution_time } =
                result.data;
              ElMessage.success(
                `清理完成！清理了 ${cleared_count} 条缓存，释放内存 ${memory_freed_human}，耗时 ${execution_time?.toFixed(
                  2
                )} 秒`
              );
              // 清理后刷新列表
              fetchAssetList();
            } catch (error: any) {
              ElMessage.error(error?.message || "清理失败");
            } finally {
              instance.confirmButtonLoading = false;
              done();
            }
          } else {
            done();
          }
        },
      }
    );
  } catch {
    // 用户取消操作
  }
};

// 清理任务缓存
const handleClearTaskCache = async (taskId: number) => {
  try {
    await ElMessageBox.confirm(
      `确定要清理任务 #${taskId} 的所有缓存吗？此操作不可恢复。`,
      "确认清理",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              const result = await clearTaskCache(taskId);

              const { cleared_count, memory_freed_human, execution_time } =
                result.data;
              ElMessage.success(
                `清理完成！清理了 ${cleared_count} 条缓存，释放内存 ${memory_freed_human}，耗时 ${execution_time?.toFixed(
                  2
                )} 秒`
              );
              // 清理后刷新列表
              fetchAssetList();
            } catch (error: any) {
              ElMessage.error(error?.message || "清理失败");
            } finally {
              instance.confirmButtonLoading = false;
              done();
            }
          } else {
            done();
          }
        },
      }
    );
  } catch {
    // 用户取消操作
  }
};

// 初始化
onMounted(() => {
  fetchAssetList();
});
</script>

<style scoped lang="scss">
.pan-assets-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .stats-card,
  .filter-card,
  .table-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .page-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
    }

    .header-actions {
      display: flex;
      gap: 10px;
    }
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #444;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .stats-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .filter-content {
    padding: 5px 0;
  }

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;

    .list-title {
      font-size: 16px;
      font-weight: 500;
      margin: 0;
      color: #303133;
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 10px;

      .sort-label {
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .table-wrapper {
    min-height: 200px;
  }

  .filename-cell {
    display: flex;
    align-items: center;
    gap: 8px;

    .file-icon {
      font-size: 16px;
    }

    .filename-text {
      font-weight: 500;
      color: #303133;
    }
  }

  .file-meta {
    margin-top: 4px;
    font-size: 12px;
    color: #909399;

    .meta-item {
      margin-right: 12px;
    }
  }

  .risk-cell {
    display: flex;
    align-items: center;
    justify-content: center;

    .risk-score {
      font-weight: 600;
      color: #303133;
    }
  }

  .person-name {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
  }

  .no-data,
  .no-risk {
    color: #909399;
    font-size: 12px;
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .action-buttons {
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
